/**
 * 公共脚本
 * Created by koal on 2017/10/11.
 */

define(['jquery', 'jqValidate', 'msgTool', 'jqValidateCN', 'AIO_App', 'AIO_Main', 'AIO_Camera', 'AIO_mainScreen'], function ($, _, msgTool) {

    return function () {

        //适配一体机屏幕高度，低于900，添加滚动条
        if ($(window).height() >= 800) {
            $("body").css({"overflow-y": "auto", "overflow-x": "auto", "width": "100%", "height": "800"});
        }

        //检测是否一体机环境，如果报错，就会执行catch代码
        if (window.isAIO === undefined) {
            try {
                get_info();
                //window.external.clear_cache();
                window.isAIO = true;
                //并关闭摄像头
                closeCamera();
                //设置提示
                //
            }
            catch (err) {
                window.isAIO = false;
            }
        }
        
        if(window.isAIO){
        	  $("#webIndex").attr('hidden', 'hidden');//隐藏web导航
        }else{
        	$("#raioIndex").attr('hidden', 'hidden');//隐藏一体机导航
        }


        //表单验证小图标
        window.errorIcon = "<i class=\"iconfont icon-error\"></i>";
        window.successIcon = "<i class=\"iconfont icon-success\"></i>";


        //表单验证  默认验证配置参数
        $.validator.setDefaults({
            highlight: function (e) {
                $(e).closest(".form-group>div").removeClass("has-success").addClass("has-error")
            },
            success: function (e) {
                e.closest(".form-group>div").removeClass("has-error").addClass("has-success")
            },
            errorElement: "div",
            errorPlacement: function (e, r) {
                // e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
                var append;
                if (r.is(":radio") || r.is(":checkbox")) {
                    append = r.parent().parent();
                } else if (r.parent().hasClass("input-group")) {
                    append = r.parent().parent();
                } else {
                    append = r.parent();
                }
                e.appendTo(append);
            },
            // errorClass: "text-danger pull-left",
            // validClass: "text-success pull-left",
            // errorClass: "help-block pull-left",
            // validClass: "help-block pull-left",
            focusInvalid: true, //当为false时，验证无效时，没有焦点响应
            onkeyup: false
        });


        /**
         * 打开输入法框
         * @param eleID
         */
        function imeOpen(eleID) {
            var info = $(eleID).val();
            var ispassword;
            var isNumber;
            //判断当前输入框的type类型
            var eleType = $(eleID).attr("type");
            var eleRows = $(eleID).attr("rows");
            if (eleRows >= 1 || eleType === "text" || eleType === "number" || eleType === "email" || eleType === "search" || eleType === "tel" || eleType === "url") {
                ispassword = 0;
            } else if (eleType === "password") {
                ispassword = 1;
            } else {
                //其他控件，不再显示
                return;
            }

            if (eleType === "number" || eleType === "tel") {
                isNumber = true;
            }

            var data = JSON.stringify({'info': info, 'ispassword': ispassword});
            var numberData = JSON.stringify({'info': info, "imetype": 0, "length": 0});
            send_command(
                isNumber ? "ime_number" : "imewrite",
                isNumber ? numberData : data,
                function (receivedData) {
                    var data = JSON.parse(receivedData);
                    if (data.status === 100) {
                        $(eleID).val(data.msg);
                    }
                    else {
                        msgTool.error(data.msg);
                    }
                }
            );
        }


        /**
         * 关闭高拍仪-事件委托方式
         */
        $("body").on("click", ".close_camera", function () {
            if (window.isAIO !== undefined && window.isAIO) {
                closeCamera();
            }
        });


        /**
         * 打开高拍仪(A3，A4,身份证)事件委托方式
         */
        $("body").on('click', '.open_camera', function () {
            var openType = $(this).data("open-type");
            //var layoutX = $(window).width() / 4;
            var layoutX = 10;
            var layoutY = 10;
            var layoutWidth = 400;
            var layoutHeight = 200;

            //如果是身份证
            if (openType === 2) {
                layoutX = $("#location-box").width() / 2 + 220;
                layoutY = 130;
                layoutWidth = $("#location-box").width() / 2;
                layoutHeight = $("#location-box").width() / 4;
            } else {
                layoutX = $(window).width() / 4;
                layoutY = 60;
                layoutWidth = $("#location-box").width() / 2;
                layoutHeight = $("#location-box").width() / 4;

                // layoutX = ($(window).width() - $("#location-box").width()) / 2;
                // layoutWidth = $("#location-box").width();
                // layoutHeight = $("#location-box").width() / 2;
            }


            var setJson = {
                //打开摄像头预览方式（0：A3预览，1：A4预览，2：身份证预览）
                "openType": openType,
                //预览窗口布局左上角 x 坐标值
                "layoutX": parseInt(layoutX),
                //预览窗口布局左上角 y 坐标值
                "layoutY": parseInt(layoutY),
                //预览窗口布局的宽度
                "layoutWidth": parseInt(layoutWidth),
                //预览窗口布局的高度 A4的宽高比例是2:1
                "layoutHeight": parseInt(layoutHeight),
                //选择摄像头（0：前置摄像头，1：高拍仪）
                "choiceCamera": 1
            };
            var data = JSON.stringify(setJson);
            //设置消息样式
            msgTool.options = {
                "positionClass": "toast-bottom-right",
                "timeOut": "5000"
            };
            send_command(
                "openCamera",
                data,
                function (receivedData) {
                    var backinfo = JSON.parse(receivedData);
                    if (backinfo.status === 100) {
                        msgTool.success("高拍仪打开成功", "提示");
                        show_ca();
                    } else if (backinfo.status === 300) {
                        msgTool.error("高拍仪模块未开启", "提示");
                    } else if (backinfo.status === 200) {
                        msgTool.error("高拍仪打开失败" + backinfo.msg, "提示");
                    }
                }
            );
        });


        /**
         * 打开高拍仪(A3，A4,身份证)事件委托方式
         */

        /**
         * 采用事件委托方式，监控页面所有加了class=form-control的输入框
         * 此方式对动态创建的元素也有效果。
         */
        $("body").on('click', '.form-control', function () {
            try {
                if ($(this).attr("readonly") !== 'readonly') {
                    imeOpen($(this));
                }
            }
            catch (err) {
            }
        });


        // 用户
        $.validator.addMethod("valiName", function (value, element) {
            return this.optional(element) || /^[a-zA-Z]{1}[a-zA-Z0-9-_]{3,19}$/m.test(value);
        }, errorIcon + "账号由4个以上字符和下划线组成！");

        // 用户
        $.validator.addMethod("valiNickName", function (value, element) {
            return this.optional(element) || /^[\u4e00-\u9fa5]{2,10}|^[a-zA-Z0-9\u4e00-\u9fa5]{1}[a-zA-Z0-9-\u4e00-\u9fa5_]{3,19}$/m.test(value);
        }, errorIcon + "账号由4个以上字符和下划线组成！");

        // 密码
        $.validator.addMethod("valiPassword", function (value, element) {
            return this.optional(element) || /^[a-zA-Z0-9]{1}[a-zA-Z0-9~!@#_\\.]{5,18}$/m.test(value);
        }, errorIcon + "密码由6-18位英文、数字或~!@#_.符号组成！");

        // 手机号
        $.validator.addMethod("valiPhone", function (value, element) {
            return this.optional(element) || /^1[356789]\d{9}$/m.test(value);
        }, errorIcon + "手机号由11位数字组成！");

        // 用户邮箱
        $.validator.addMethod("vailNameEmail", function (value, element) {
            return this.optional(element) || /^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}$/m.test(value);
        }, errorIcon + "账号或邮箱格式错误！");

        // 用户手机号邮箱
        $.validator.addMethod("vailNamePhoneEmail", function (value, element) {
            return this.optional(element) || /^[a-zA-Z]{1}[a-zA-Z0-9-_]{3,19}$|\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}$|^1[356789]\d{9}$/m.test(value);
        }, errorIcon + "账号、手机号或邮箱格式错误！");

        // 不能包含中文
        $.validator.addMethod("vailEnName", function (value, element) {
            return this.optional(element) || /^[^\u4e00-\u9fa5]+$/m.test(value);
        }, errorIcon + "不能包含中文字符！");

        // 邮箱
        $.validator.addMethod("vailEmail", function (value, element) {
            return this.optional(element) || /^(\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14})$/m.test(value);
        }, errorIcon + "电子邮箱格式错误！");

        // 验证码
        $.validator.addMethod("vailImgCode", function (value, element) {
            return this.optional(element) || /^[A-Za-z0-9]{4}$/.test(value);
        }, errorIcon + "验证码格式错误！");
    }
});

/**
 * base64 上传后，转换成 图片url地址
 * @param base64Code
 * @param elementId
 */
function updateBase64(base64Code, elementId) {
    var result = {};
    $.ajax({
        url: "/common/uploader/base64",
        type: 'POST',
        async: false,
        data: {
            base64Code: base64Code
        },
        dataType: "JSON",
        success: function (data) {
            if (data.status) {
                result = data;
            } else {
                result = {status: false, message: '图片上传失败'};
            }
        },
        error: function (err) {
            result = {status: false, message: '图片上传失败'};
        }
    });
    return result;
}

/**
 * 打开广告屏幕
 *
 */
//打开副屏（宣传页）
function openViceAdvertising(webUrl) {
    var info = get_info();
    info = JSON.parse(info);
    webUrl = webUrl + 'ad/' + info.M_Tag;
    // url='http://zhll-web.i2works.com//ad/'+info.M_Tag;
    var data = {
        'url': webUrl
    };
    data = JSON.stringify(data);
    send_command(
        "open_vice_url", // 方法名
        data, // 传入参数
        function (receivedData) {
            var st = JSON.parse(receivedData);
            if (st.status == 100) {
                //  Toast('res', '副屏（宣传页）打开成功');
            } else if (st.status == 200) {
                //   Toast('err', '副屏（宣传页）打开失败：' + st.msg);
            }
        }
    );
}
